//创建和初始化地图函数：
 function initMap(){
	createMap();//创建地图
    setMapEvent();//设置地图事件
    addMapControl();//向地图添加控件
}
//创建地图函数：
function createMap(){
    var map = new BMap.Map("dituContent");//在百度地图容器中创建一个地图
    var Points = new BMap.Point(113.750028,34.718262);//定义一个中心点坐标
    map.centerAndZoom(Points,10);//设定地图的中心点和坐标并将地图显示在地图容器中
    window.map = map;//将map变量存储在全局
}
//地图事件设置函数：
function setMapEvent(){
	map.enableDragging();//启用地图拖拽事件，默认启用(可不写)
	map.enableScrollWheelZoom();//启用地图滚轮放大缩小
	map.enableDoubleClickZoom();//启用鼠标双击放大，默认启用(可不写)
	map.enableKeyboard();//启用键盘上下左右键移动地图
}
//地图控件添加函数：
function addMapControl(){
    //向地图中添加缩放控件
	var ctrl_nav = new BMap.NavigationControl({anchor:BMAP_ANCHOR_TOP_LEFT,type:BMAP_NAVIGATION_CONTROL_LARGE});
	map.addControl(ctrl_nav);    
    //向地图中添加比例尺控件
	var ctrl_sca = new BMap.ScaleControl({anchor:BMAP_ANCHOR_BOTTOM_LEFT});
	map.addControl(ctrl_sca);
};
initMap();//创建和初始化地图

// li 导航收起
$("#shouqitop").click(function(){
		$(".top").slideToggle();
});

$("#shouqiright").click( function ()
{
		$(".right").toggleClass("aaa");	
});

// workerman 实时数据接收
var markers2 = [];
var markerClusterer2 = null;
var data_stuts = false;
$(document).ready(function(){
    // 连接服务端
    var socket = io('http://lot.iqykj.com:2120');
    // 连接后登录
   	uid = "";
    // 用户登录后,告诉后台有有用户登录
    socket.on('connect', function()
    {
    	socket.emit('login', uid);
    });
    // 后端推送来消息时 执行此方法
    socket.on('new_msg', function(msg)
    {
    	var smoke_data;
    	var msg_data;
    	var r_type;
		// 声明地图空数组,用于压入地图图标信息
		// 正则匹配,从新拼装json字符串
        var rule = /&quot;/g;
        var str_json = msg.replace(rule,'"');
        msg_data = jQuery.parseJSON(str_json);
        var mote = msg_data['rxpk']['mote'].datar;
        // ajax 请求后台数据,返回json格式
	    $.ajax(
	    {
			type:"get",
			url:"/admin/rvceo/worker",
			async:false,
			data:{Jstr:str_json},
			dataType:"html",
			success:function(jstr)
			{ // 如果ajax请求成功,执行此方法
				if(jstr){
					smoke_data = jQuery.parseJSON(jstr);
					r_type = "<font size='2'>报警类型:"+smoke_data.r_type+"</font><br />";
					var redpt =new BMap.Point(smoke_data.lng,smoke_data.lat); // 创建图标位置
					var myIcon = new BMap.Icon('/admin/img/yangan_error.gif', new BMap.Size(120,120));  // 引入图标
					var marker = new BMap.Marker(redpt,{icon:myIcon}); // 创建标注图标
					markers2.push(marker); // 将标注添加到地图数组中
					markerClusterer2 = new BMapLib.MarkerClusterer(map,{markers:markers2}); // 将图标放入地图
					var opts = {
						width : 200, // 信息窗口的宽度
						height : 120, // 信息窗口高度
						title : smoke_data.name, // 信息窗口标题
					};
					var infoWindow = new BMap.InfoWindow(r_type+"<font size = '2'>地址:"+smoke_data.room+"</font><br /><font size ='2'>联系人:"+smoke_data.username+"</font><br /><font size='2'>电话:"+smoke_data.phone+'</font>',opts); // 创建信息窗口对象
					
					map.openInfoWindow(infoWindow,redpt); // 开启信息窗口
					// });
					$('#yjbjon').attr('src','/admin/img/alarmon.png');
					$('#newMessageDIV').html('<audio autoplay="autoplay" loop=-1><source src="/admin/voice/1.WAV"' + 'type="audio/wav"/><source src="/admin/voice/1.mp3" type="audio/mpeg"/></audio>');
					data_stuts =true;
					var removeMarker = function(e,ee,marker)
					{
						map.removeOverlay(markers2);
						$('#newMessageDIV').empty();
						markers2.push(0); //将地图数组中的数据写为0
						var markers1 = markers2.slice(markers2.length,0);
						markerClusterer2.clearMarkers();         //此步骤需要
						markerClusterer2 = new BMapLib.MarkerClusterer(map, {markers:markers1});
					}
					var markerMenu=new BMap.ContextMenu();
					markerMenu.addItem(new BMap.MenuItem('删除',removeMarker.bind(markers2)));
					marker.addContextMenu(markerMenu);
					if(smoke_data.url){
						if($('#camera_url').length == 0){
                            var str = "<object type='application/x-vlc-plugin' id='vlc' events='True' width='400' height='230' pluginspage='http://www.videolan.org' codebase='http://downloads.videolan.org/pub/videolan/vlc-webplugins/2.0.6/npapi-vlc-2.0.6.tar.xz'> <param id='camera_url' name='mrl' value='"+smoke_data.url+"'/> <param name='volume' value='50' /> <param name='autoplay' value='true' /> <param name='loop' value='false' /> <param name='fullscreen' value='false' /> </object>";
                            $('#camera').append(str);
                            $('#camera').css('display','block');
						}
					}
				}
			}
		});
	});
// 柱状图
$.ajax(
	    {
			type:"get",
			url:"/admin/rvceo/histogram",
			async:false,
			dataType:"json",
			success:function(jstr)
			{  var chart;

            var chartData = [
               {
                    " type": "自检",
                    "visits": 5,
                    "color": "#FF0F00"
                },
                {
                    " type": "防拆警报",
                    "visits": 1,
                    "color": "#FF6600"
                },
                {
                    " type": "火灾报警",
                    "visits": 5,
                    "color": "#FF9E01"
                },
                {
                    " type": "欠压报警",
                    "visits": 1,
                    "color": "#FCD202"
                },
                {
                    " type": "故障报警",
                    "visits": 4,
                    "color": "#F8FF01"
                }
            ];


            AmCharts.ready(function () {
                // SERIAL CHART
                chart = new AmCharts.AmSerialChart();
                chart.dataProvider = chartData;
                chart.categoryField = " type";
                chart.startDuration = 1;

                // AXES
                // category
                var categoryAxis = chart.categoryAxis;
                categoryAxis.labelRotation = 45; // this line makes category values to be rotated
                categoryAxis.gridAlpha = 0;
                categoryAxis.fillAlpha = 1;
                categoryAxis.fillColor = "#FAFAFA";
                categoryAxis.gridPosition = "start";

                // value
                var valueAxis = new AmCharts.ValueAxis();
                valueAxis.dashLength = 5;
                valueAxis.title = "";
                valueAxis.axisAlpha = 0;
                chart.addValueAxis(valueAxis);

                // GRAPH
                var graph = new AmCharts.AmGraph();
                graph.valueField = "visits";
                graph.colorField = "color";
                graph.balloonText = "<b>[[category]]: [[value]]</b>";
                graph.type = "column";
                graph.lineAlpha = 0;
                graph.fillAlphas = 1;
                chart.addGraph(graph);

                // CURSOR
                var chartCursor = new AmCharts.ChartCursor();
                chartCursor.cursorAlpha = 0;
                chartCursor.zoomable = false;
                chartCursor.categoryBalloonEnabled = false;
                chart.addChartCursor(chartCursor);

                chart.creditsPosition = "top-right";

                // WRITE
                chart.write("chartdiv");
            });
			}
		});


});
function form(lg){
	var point;
	var num =0;
	var markers = [];  // 声明地图空数组,用于压入地图图标信息
	var markerClusterer = null;
	// 判断第几个li 标签,匹配图片
	switch(lg)
	{
		case 0:
			var imgioc = 'jizhanioc.png';
			var imgon = 'jizhanon.png';
			var imgoff = 'jizhanoff.png';
			break;
		case 1:
			var imgioc = 'yanganioc.png';
			var imgon = 'yanganon.png';
			var imgoff = 'yanganoff.png';
			break;
		case 2:
			var imgioc = 'hongwaiioc.png';
			var imgon = 'hongwaion.png';
			var imgoff = 'hongwaioff.png';
			break;
		case 3:
			var imgioc = 'ranqiioc.png';
			var imgon = 'ranqion.png';
			var imgoff = 'ranqioff.png';
			break;
		case 4:
			var imgioc = 'electricioc.png';
			var imgon = 'electricon.png';
			var imgoff = 'electricoff.png';
			break;
		case 5:
			var imgioc = 'call_help_ioc.png';
			var imgon = 'call_help_on.png';
			var imgoff = 'call_help_off.png';
			break;
		case 12:
			msg_woarn = true;
			break;
		default:
			return false;
	}
	// 点击单个li标签
	$('li:eq('+lg+')').click(function()
	// {
		// console.log(lg);
	{
		// 如果这个标签是第12个并且data_stuts标记为真 
		if(lg ==12&&data_stuts)
		{ //执行
			//取消摄像头
            $('#camera').empty();
            $('#camera').css('display','none');
			// 移除markers2
			map.removeOverlay(markers2);
			// 去除'#newMessageDIV'样式
			$('#newMessageDIV').empty();
			markers2.push(0); //将地图数组中的数据写为0
			var markers1 = markers2.slice(markers2.length,0);  
			markerClusterer2.clearMarkers();         //此步骤需要  
			markerClusterer2 = new BMapLib.MarkerClusterer(map, {markers:markers1});
			$(this).children().attr('src','/admin/img/alarmoff.png');
			map.closeInfoWindow();
		}else{
			$.ajax(
			{
				type:"get",
				url:"/admin/rvceo/data",
				async:false,
				data:{"Type":lg},
				dateType:"json",
				success:function(str){
					if(str){
						point =jQuery.parseJSON(str);
					}else{
						point = '';
					}
				}
			});
			if(point!='')
			{
				if(num++ % 2 ===0)
				{ //当 单击时执行表达式
					$.each(point,function(index,value)
					{	
						var redpt =new BMap.Point(value.longitude,value.latitude); // 创建图标位置
						var myIcon = new BMap.Icon('/admin/img/'+imgioc, new BMap.Size(44,44));  // 引入图标
						var marker = new BMap.Marker(redpt,{icon:myIcon}); // 创建标注图标
						markers.push(marker); // 将标注添加到地图数组中
					});
					markerClusterer = new BMapLib.MarkerClusterer(map,{markers:markers}); // 将图标放入地图
					$(this).children().attr('src','/admin/img/'+imgon); // li标签 设备打开样式	
				}else{
					$.each(point,function(index,value)
					{ // 遍历point
						map.removeOverlay(markers[index]); 
		    			markers.push(0); //将地图数组中的数据写为0
		    		}); 
		    		var markers1 = markers.slice(markers.length,0);  
					markerClusterer.clearMarkers();         //此步骤需要  
					markerClusterer = new BMapLib.MarkerClusterer(map, {markers:markers1});
					$(this).children().attr('src','/admin/img/'+imgoff); // 设备关闭样式
				}
			}else{
				return false;
			}
		}
	});
}

// 遍历标签
$('li').each(function(i)
{//匹配方法
	form(i);
});	




//绘制饼状图 
var pieData = [
	{
		value: 300,
		color:"#36A2EB",
		label: "用户不慎"
	},
	{
		value: 50,
		color: "#4BC0C0",
		label: "家用电器"
	},
	{
		value: 100,
		color: "#FF9F40",
		label: "违规操作"
	},
	{
		value: 40,
		color: "#FF6384",
		label: "吸烟"
	},
	{
		value: 120,
		color: "#FFCD56",
		label: "故意纵火"
	},
	{
		value: 70,
		color: "#66FF99",
		label: "自燃"
	},
	{
		value: 220,
		color: "#D6D6D6",
		label: "其他"
	}
];		
var ctx = document.getElementById("chart-area").getContext("2d");
window.myPie = new Chart(ctx).Pie(pieData);